package com.gao.web.controller;

import com.gao.web.pojo.Customer;
import com.gao.web.service.UserService;
import com.google.gson.Gson;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/customerfindall")
public class CustomerfindAllServlet extends HttpServlet {
    private UserService userService;

    @Override
    public void init() throws ServletException {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
        userService = context.getBean(UserService.class);
    }

    protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<Customer> customers = userService.customerfindall();
        List<Map<String, Object>> recordList = new ArrayList<>();
        for (Customer customer : customers) {
            Map<String, Object> recordMap = new HashMap<>();
            recordMap.put("id", customer.getId());
            recordMap.put("username", customer.getUsername());
            recordMap.put("password", customer.getPassword());
            recordMap.put("name", customer.getName());
            recordMap.put("phone", customer.getPhone());
            recordMap.put("address", customer.getAddress());
            recordMap.put("ID_number", customer.getID_number());
            recordMap.put("birth_date", customer.getBirth_date());
            recordMap.put("sex", customer.getSex());
            recordMap.put("email", customer.getEmail());
            // 以此类推，将每个字段名和字段值存入Map
            recordList.add(recordMap);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("code", 0); // 设置响应状态码，0 表示成功
        result.put("msg", ""); // 设置响应消息，这里可以不设置
        result.put("count", recordList.size()); // 设置数据总数
        result.put("data", recordList); // 设置数据列表

        //将获取的数据转换为json格式
        Gson gson = new Gson();
        String resultJson = gson.toJson(result);
        Map<String, Object> map = new HashMap<>();
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(resultJson); // 将数据以 JSON 格式返回
    }
}

